package ucap.com.lesanapp.base.impl;

import android.app.Activity;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Vibrator;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.bingoogolapple.bgabanner.BGABanner;
import ucap.com.lesanapp.R;
import ucap.com.lesanapp.activitys.NewsDetailedActivity;
import ucap.com.lesanapp.base.BasePager;
import ucap.com.lesanapp.bean.DateBean;
import ucap.com.lesanapp.bean.TopNewHeadBean;
import ucap.com.lesanapp.global.Constants;
import ucap.com.lesanapp.global.SettingsModelState;
import ucap.com.lesanapp.utils.NetworkStateUtils;
import ucap.com.lesanapp.utils.PrefUtils;
import ucap.com.lesanapp.view.WebViewDialog;


/**
 * Created by Administrator on 2016/7/27.
 * 要闻
 */
public class FocusNewsBase extends BasePager {
    @Bind(R.id.lv_focus_news)
    ListView lvContent;
    @Bind(R.id.ll_focus_loading)
    LinearLayout llLoading;
    @Bind(R.id.sr_refresh)
    SwipeRefreshLayout srRefresh;
    ArrayList<DateBean.RowsBean> mListDate;
    private MyAdapter adapter;
    private int model;
    private int networkType;
    ArrayList<TopNewHeadBean.RowsBean> mTopNewsHeadList;
    private BGABanner banner;
    private TextView tvTopNewsTitle;
    private BitmapUtils bitmapUtils;
    private View head;


    public FocusNewsBase(Activity mActivity) {
        super(mActivity);
    }

    @Override
    public void intiDate() {
        View view = View.inflate(mActivity, R.layout.base_focus_news, null);
        ButterKnife.bind(this, view);
        flContent.addView(view);
    }

    @Override
    public void intiDateForService() {
        llLoading.setVisibility(View.VISIBLE);
        srRefresh.setVisibility(View.INVISIBLE);
        getType();
        addListViewHeadView();//添加头条
        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                /**
                 将头部itemID减去,排除用户点击底部发生角标越界
                 */
                int index = position - 1;
                if (index >= 0 && index < mListDate.size()) {
                    DateBean.RowsBean item = adapter.getItem(index);
                    Intent intent = new Intent(mActivity, NewsDetailedActivity.class);
                    intent.putExtra("title", item.getCHANNELNAME());
                    intent.putExtra("code", item.getID());
                    intent.putExtra("head", item.getTITLE());
                    intent.putExtra("cid", Constants.ID_FOCUS_NEW);
                    mActivity.startActivity(intent);
                }
            }
        });
        lvContent.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                Vibrator vibrator = (Vibrator) mActivity.getSystemService(mActivity.VIBRATOR_SERVICE);
                vibrator.vibrate(60);
                if (position < mListDate.size()) {
                    DateBean.RowsBean item = adapter.getItem(position);
                    WebViewDialog.showDialog(mActivity, item.getID(), item.getTITLE(), Constants.ID_FOCUS_NEW);
                }
                return true;
            }
        });
        srRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                getImagesForService();//刷新轮播数据
                getDateFromService();//刷新新闻数据
                getType();
                headModel();//头条数据是否刷新
            }
        });
        String cacheDate = PrefUtils.getString("focus_news_date", "", mActivity);
        if (!cacheDate.isEmpty()) {
            analysisDate(cacheDate);
            Log.i("jsonCache", "发现本地缓存。。");
        }
        getDateFromService();
        lvContent.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
    }

    /**
     * 轮播广告
     */
    private void addListViewHeadView() {

        //轮播广告
        head = View.inflate(mActivity, R.layout.head_top_news, null);
        banner = (BGABanner) head.findViewById(R.id.banner_splash_pager);
        tvTopNewsTitle = (TextView) head.findViewById(R.id.tv_top_news_title);
        String topNewsHeadCache = PrefUtils.getString("FocusNewsHead", "", mActivity);
        if (!topNewsHeadCache.isEmpty()) {
            analysisJsonDate(topNewsHeadCache);
            Log.i("topImageCache", "轮播的缓存数据");
        }
        lvContent.addHeaderView(head);
//        lvContent.removeHeaderView(head);
        headModel();
        getImagesForService();

    }

    /**
     * 判断网络网络环境以及,阅读模式
     */
    public void getType() {
        model = PrefUtils.getInt("model", SettingsModelState.MODEL_TEXT_AND_IMAGE, mActivity);
        Log.i("model", model + "模式");
        networkType = NetworkStateUtils.network(mActivity);
        Log.i("model", networkType + "网络状态");
    }

    /**
     * 从服务器获取轮播广告的数据
     */
    public void getImagesForService() {
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpMethod.GET, Constants.URL_FOCUS_NEWS_HEAD, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                analysisJsonDate(responseInfo.result);
                PrefUtils.putString("FocusNewsHead", responseInfo.result, mActivity);
            }

            @Override
            public void onFailure(HttpException error, String msg) {

            }
        });
    }

    /**
     * 解析轮播广告数据
     *
     * @param date
     */

    public void analysisJsonDate(String date) {
        Gson gson = new Gson();
        TopNewHeadBean dateBean = gson.fromJson(date, TopNewHeadBean.class);
        mTopNewsHeadList = (ArrayList<TopNewHeadBean.RowsBean>) dateBean.getRows();
        bitmapUtils = new BitmapUtils(mActivity);
        banner.setPageChangeDuration(1000);
        banner.setAutoPlayAble(true);
        tvTopNewsTitle.setText(mTopNewsHeadList.get(0).getTITLE());//默认显示第一张
        ArrayList<View> views = new ArrayList<>();
        for (int i = 0; i < mTopNewsHeadList.size(); i++) {
            TopNewHeadBean.RowsBean rowsBean = mTopNewsHeadList.get(i);
            views.add(getPageView(rowsBean.getPATHANDURL()));
        }
        banner.setData(views);
        banner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                String title = mTopNewsHeadList.get(position).getTITLE();
                tvTopNewsTitle.setText(title);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        banner.setOnItemClickListener(new BGABanner.OnItemClickListener() {
            @Override
            public void onBannerItemClick(BGABanner banner, View view, Object model, int position) {
                if (position < mListDate.size()) {
                    TopNewHeadBean.RowsBean item = mTopNewsHeadList.get(position);
                    Intent intent = new Intent(mActivity, NewsDetailedActivity.class);
                    intent.putExtra("title", item.getCHANNELNAME());
                    intent.putExtra("code", item.getID());
                    intent.putExtra("head", item.getTITLE());
                    intent.putExtra("cid", Constants.ID_FOCUS_HEAD);
                    mActivity.startActivity(intent);
                }
            }
        });

    }

    private View getPageView(String src) {
        ImageView imageView = new ImageView(mActivity);
        bitmapUtils.display(imageView, src);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        return imageView;


    }

    /**
     * 头条根据模式设置是否显示
     */
    private void headModel() {
//        Log.i("headModel", " 当前模式:" + model);
//        if (model == SettingsModelState.MODEL_TEXT) {
//            lvContent.removeHeaderView(head);
//            Log.i("headModel", "文本模式隐藏head");
//        } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
//            //智能模式
//            if (networkType != ConnectivityManager.TYPE_WIFI) {
//                //wifi状态
//                lvContent.removeHeaderView(head);
//                Log.i("headModel", "不是WIFI不显示head");
//            } else {
//                lvContent.removeHeaderView(head);
//                lvContent.addHeaderView(head);
//                Log.i("headModel", "wifi下显示head");
//            }
//        } else if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
//            lvContent.removeHeaderView(head);
//            lvContent.addHeaderView(head);
//            Log.i("headModel", "图文模式显示head");
//        }
    }

    /**
     * 获取服务器数据
     */
    private void getDateFromService() {

        String url = Constants.URL_FOCUS_NEWS_DATES;
        HttpUtils httpUtil = new HttpUtils();
        httpUtil.send(HttpMethod.GET, url, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                analysisDate(responseInfo.result);
                Log.i("focusNewData", responseInfo.result);
                PrefUtils.putString("focus_news_date", responseInfo.result, mActivity);
                Log.i("jsonCache", "写入缓存");
                srRefresh.setRefreshing(false);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Toast.makeText(mActivity, "网络异常!", Toast.LENGTH_SHORT).show();
                srRefresh.setRefreshing(false);
            }
        });
    }

    /**
     * 解析服务数据
     *
     * @param result
     */

    private void analysisDate(String result) {
        Gson gson = new Gson();
        DateBean date = gson.fromJson(result, DateBean.class);
        mListDate = (ArrayList<DateBean.RowsBean>) date.getRows();
        adapter = new MyAdapter();
        lvContent.setAdapter(adapter);
        llLoading.setVisibility(View.GONE);
        srRefresh.setVisibility(View.VISIBLE);

    }

    class MyAdapter extends BaseAdapter {
        BitmapUtils bitmapUtils;

        MyAdapter() {
            bitmapUtils = new BitmapUtils(mActivity);
        }

        @Override
        public int getCount() {
            return mListDate.size();
        }

        @Override
        public DateBean.RowsBean getItem(int position) {
            return mListDate.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = View.inflate(mActivity, R.layout.item_date_content, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            DateBean.RowsBean date = getItem(position);

            //判断服务器是否返回图片，没有就影藏图片控件
            if (!date.getPATHANDURL().isEmpty()) {
                //图文模式
                if (model == SettingsModelState.MODEL_TEXT_AND_IMAGE) {
                    holder.ivPhoto.setVisibility(View.VISIBLE);
                    bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                } else if (model == SettingsModelState.MODEL_TEXT) {
                    //文本模式
                    holder.ivPhoto.setVisibility(View.GONE);
                } else if (model == SettingsModelState.MODEL_AUTOMATIC) {
                    //智能模式
                    if (networkType == ConnectivityManager.TYPE_WIFI) {
                        //wifi状态
                        holder.ivPhoto.setVisibility(View.VISIBLE);
                        bitmapUtils.display(holder.ivPhoto, date.getPATHANDURL());
                    } else {
                        holder.ivPhoto.setVisibility(View.GONE);
                    }
                }

            } else {
                holder.ivPhoto.setVisibility(View.GONE);
            }
            holder.tvTitle.setText(date.getTITLE());
            holder.tvTime.setText(date.getTIME());
            holder.tvType.setText(date.getCHANNELNAME());
            return convertView;
        }
    }

    public class ViewHolder {
        @Bind(R.id.iv_news_photo)
        ImageView ivPhoto;
        @Bind(R.id.tv_news_title)
        TextView tvTitle;
        @Bind(R.id.tv_news_time)
        TextView tvTime;
        @Bind(R.id.tv_news_type)
        TextView tvType;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}
